package mgo

import (
	"fmt"
	"gopkg.in/mgo.v2"
)

var session *mgo.Session

var (
	mongodbHost   = "127.0.0.1"
	mongodbPort   = 27017
	dbname        = "transfinite"
	mongodbAuthDB = "transfinite"
	mongodbUser   = ""
	mongodbPwd    = ""
	mongodbAuth   = false
)

var (
	ErrNotFound = mgo.ErrNotFound
)

// 默认配置初始化会话
func InitDefault() {
	var err error
	session, err = newSession()
	if err != nil {
		panic(err)
	}
}

// 初始化会话
func Init(host string, port int, name string, authdb, user, pwd string, auth bool) {
	var err error
	mongodbHost = host
	mongodbPort = port
	dbname = name
	mongodbAuthDB = authdb
	mongodbUser = user
	mongodbPwd = pwd
	mongodbAuth = auth

	session, err = newSession()
	if err != nil {
		panic(err)
	}
}

func newSession() (*mgo.Session, error) {
	var err error
	var url string

	if mongodbAuth {
		url = fmt.Sprintf("mongodb://%s:%s@%s:%d/%s", mongodbUser, mongodbPwd, mongodbHost, mongodbPort, mongodbAuthDB)

	} else {
		url = fmt.Sprintf("%s:%d", mongodbHost, mongodbPort)
	}

	session, err = mgo.Dial(url)
	if err != nil {
		return nil, err
	}
	session.SetMode(mgo.Monotonic, true)

	return session, nil
}

// 获取指定表名的连接
func getCollectionConn(tb string) *mgo.Collection {
	con := session.Copy().DB(dbname)
	return con.C(tb)
}

// 关闭会话
func closeConn(c *mgo.Collection) {
	c.Database.Session.Close()
}

// 关闭mongo
func StopMongo() {
	session.Close()
}
